package com.springmvc.netty.test;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

	private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
		Channel channel = ctx.channel();
		System.out.println(channelGroup.size());

		channelGroup.forEach(c -> {
			System.out.println("發了");
			if (channel == c) { // 如果自己
				channel.writeAndFlush(new TextWebSocketFrame("【自己】: " + msg.text() + "\n"));
			} else { // 发送给其他人的信息
				c.writeAndFlush(new TextWebSocketFrame(channel.remoteAddress() + ": " + msg.text() + "\n"));
			}
		});
	}

	// 连接建立
	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		Channel channel = ctx.channel(); // 获取到上线的连接
		channelGroup.writeAndFlush(new TextWebSocketFrame("【服务器】: " + channel.remoteAddress() + "上线\n")); // 服务器发送广播通知
		channelGroup.add(channel); // 将通道添加到组
	}

	// 连接断开
	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
		Channel channel = ctx.channel();
		channelGroup.writeAndFlush(new TextWebSocketFrame("【服务器】: " + channel.remoteAddress() + "下线了\n"));
		channelGroup.remove(channel);
	};

	// 连接激活
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		System.out.println(ctx.channel().remoteAddress() + "上线了");
		channelGroup.writeAndFlush(new TextWebSocketFrame("【服务器】: " + ctx.channel().remoteAddress() + "连接激活\n"));
	}

	// 连接断开
	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		System.out.println(ctx.channel().remoteAddress() + "下线了");
		channelGroup.writeAndFlush(new TextWebSocketFrame("【服务器】: " + ctx.channel().remoteAddress() + "连接断开\n"));
	};

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		Channel incoming = ctx.channel();
		System.out.println("Client:" + incoming.remoteAddress() + "异常");
		cause.printStackTrace();
		ctx.close();
	}

}